package developer.算法.链表.合并两个有序链表;

/**
 * @author zhangyongkang
 * @time 2025/3/20 10:54
 * @description 1 = [1,2,4], l2 = [1,3,4]
 * 输出：[1,1,2,3,4,4]
 * <p>
 * 将两个升序链表合并为一个新的 升序 链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的。
 */
public class HeBingLiangGeYouXuLianBiao {

    public static void main(String[] args) {
        ListNode listNode = mergeTwoLists(
                new ListNode(1, new ListNode(2, new ListNode(3, new ListNode(4)))),
                new ListNode(1, new ListNode(2, new ListNode(3, new ListNode(4))))
        );
        System.out.println(listNode);
    }

    public static ListNode mergeTwoLists(ListNode list1, ListNode list2) {
        if (list1 == null) {
            return list2;
        }
        if (list2 == null) {
            return list1;
        }
        ListNode list1Current = list1;
        ListNode list2Current = list2;

        ListNode head = null;
        ListNode current = null;

        while (list1Current != null || list2Current != null) {
            if (list1Current == null) {
                current.next = list2Current;
                current = current.next;
                list2Current = list2Current.next;
                continue;
            }
            if (list2Current == null) {
                current.next = list1Current;
                current = current.next;
                list1Current = list1Current.next;
                continue;
            }
            int va1 = list1Current.val;
            int va2 = list2Current.val;
            boolean firstIsBig = va1 >= va2;

            if (head == null) {
                if (firstIsBig) {
                    head = new ListNode(va2);
                } else {
                    head = new ListNode(va1);
                }
                current = head;
            } else {
                if (firstIsBig) {
                    current.next = list2Current;
                } else {
                    current.next = list1Current;
                }
                current = current.next;
            }

            if (firstIsBig) {
                list2Current = list2Current.next;
            } else {
                list1Current = list1Current.next;
            }
        }

        return head;
    }


    public static class ListNode {
        int val;
        ListNode next;

        ListNode() {
        }

        ListNode(int val) {
            this.val = val;
        }

        ListNode(int val, ListNode next) {
            this.val = val;
            this.next = next;
        }
    }

    class Solution {
        public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
            if (l1 == null) {
                return l2;
            } else if (l2 == null) {
                return l1;
            } else if (l1.val < l2.val) {
                l1.next = mergeTwoLists(l1.next, l2);
                return l1;
            } else {
                l2.next = mergeTwoLists(l1, l2.next);
                return l2;
            }
        }
    }

}
